package com.xusheng.cli.controller.proxy;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xusheng.cli.common.base.MyPage;
import com.xusheng.cli.common.base.Result;
import com.xusheng.cli.common.validation.Update;
import com.xusheng.cli.entity.frontUserModule.FrontUser;
import com.xusheng.cli.entity.vipRecordModule.VipRecord;
import com.xusheng.cli.service.BackAgentService;
import com.xusheng.cli.service.FrontUserService;
import com.xusheng.cli.service.VipConfigService;
import com.xusheng.cli.service.VipRecordService;
import com.xusheng.cli.tools.CurrentProxyUserUtil;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.LocalTime;

/**
 * @author lyh
 * @since 2023-04-26 15:40
 */
@RestController
@RequestMapping("/proxy/v1/frontUser")
public class FrontUserController {

    @Resource
    private FrontUserService frontUserService;
    @Resource
    private BackAgentService backAgentService;
    @Resource
    private VipConfigService vipConfigService;
    @Resource
    private VipRecordService vipRecordService;

    /**
     * 通过条件查询用户列表
     *
     * @param req 查询条件
     * @return 返回结果
     */
    @GetMapping("queryByPage")
    public Result<MyPage<FrontUser>> list(MyPage<FrontUser> page, FrontUser frontUser) {
        Long userId = CurrentProxyUserUtil.getUserId();
        LocalDateTime start = null, end = null;
        if (frontUser.getStartTime() != null) {
            start = LocalDateTime.of(frontUser.getStartTime(), LocalTime.of(0, 0, 0));
        }
        if (frontUser.getEndTime() != null) {
            end = LocalDateTime.of(frontUser.getEndTime(), LocalTime.of(23, 59, 59));
        }
        MyPage<FrontUser> page1 = frontUserService.page(page, new LambdaQueryWrapper<>(new FrontUser())
                .inSql(FrontUser::getProxyId, StrUtil.format("SELECT" +
                        " id " +
                        "FROM " +
                        " back_agent " +
                        "WHERE\n" +
                        "\tdeleted = 0 \n" +
                        "\tAND state = 1 \n" +
                        "\tAND parent_id IN ( SELECT id FROM back_agent WHERE parent_id = '{}' AND deleted = 0 AND " +
                        "state = 1 ) UNION ALL " +
                        "SELECT\n" +
                        "\tid \n" +
                        "FROM\n" +
                        "\tback_agent \n" +
                        "WHERE\n" +
                        "\tparent_id = '{}' \n" +
                        "\tAND deleted = 0 \n" +
                        "\tAND state = 1 UNION ALL\n" +
                        "SELECT\n" +
                        "\t'{}'", userId, userId, userId))
                .gt(start != null, FrontUser::getCreateTime, start)
                .lt(end != null, FrontUser::getCreateTime, end)
                .eq(StrUtil.isNotBlank(frontUser.getInviteCode()), FrontUser::getInviteCode, frontUser.getInviteCode())
                .like(StrUtil.isNotBlank(frontUser.getHost()), FrontUser::getHost, frontUser.getHost())
                .like(StrUtil.isNotBlank(frontUser.getAccount()), FrontUser::getAccount, frontUser.getAccount()));
        for (FrontUser frontUser1 : page1.getRecords()) {
            if (frontUser1.getProxyId() != null) {
                frontUser1.setProxyName(backAgentService.getById(frontUser1.getProxyId()).getName());
            }
            if (frontUser1.getVipId() != null) {
                frontUser1.setVipName(vipConfigService.getById(frontUser1.getVipId()).getName());
            }
            frontUser1.setVipCount(Math.toIntExact(vipRecordService.lambdaQuery().eq(VipRecord::getUserId, frontUser1.getId()).count()));
        }
        return Result.success(page1);
    }

    /**
     * 通过id获取信息
     *
     * @param id 编号
     * @return 返回结果
     */
    @GetMapping("/{id}")
    public Result<FrontUser> info(@PathVariable long id) {
        FrontUser user = frontUserService.getById(id);
        return Result.success(user);
    }

    /**
     * 更新用户信息
     *
     * @param user 用户信息
     * @return 返回结果
     */
    @PutMapping("")
    public Result<Object> update(@Validated(Update.class) @RequestBody FrontUser user) {
        if (StrUtil.isNotBlank(user.getPassword())) {
            user.setPassword(DigestUtil.bcrypt(user.getPassword()));
        }
        return Result.isSuccess(frontUserService.updateById(user));
    }
}
